<!DOCTYPE html>
<html>
<head>
	<title>banner页配置</title>
</head>

<style type="text/css">
.btn{
    color: #fff;
    background-color: #337ab7;
    border-color: #2e6da4; 
    display: inline-block;
    padding: 6px 12px;
    margin-bottom: 0;
    font-size: 14px;
    font-weight: 400;
    line-height: 1.42857143;
    text-align: center;
    white-space: nowrap;
    text-decoration: none;
    vertical-align: middle;
    -ms-touch-action: manipulation;
    touch-action: manipulation;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    background-image: none;
    border: 1px solid transparent;
    border-radius: 4px;
}
a.btn:hover{
  background-color: #3366b7;
}

.banner-img {
	width: 500px;
	height: 300px;
}

.form-panel {
	width: 500px;
	margin-left: auto;
	margin-right: auto;
}

</style>

<body>

<div class="form-panel">
<form method="post" action="/index.php/Admin/Index/uploadBannerInfo">

	<?php
		for ($i = 0; $i < $bannerNum; $i++) {
	?>

	<img class="banner-img" id="banner{$i}" src="<?php echo array_key_exists($i, $banners) ? $banners[$i]['src'] : '/static/imgs/default.jpg'; ?> ">
	<input type="text" id="imgsrc{$i}" name="images[]" value="<?php echo array_key_exists($i, $banners) ? $banners[$i]['src'] : ''; ?>">
	<input type="file" id="img{$i}" onchange="previewImg('banner{$i}', this.id)">
	<input type="text" name="urlPaths[]" value="<?php echo array_key_exists($i, $banners) ? $banners[$i]['url'] : ''; ?>">
	<a href="javascript:ossUpload('img{$i}', 'banner{$i}', 'imgsrc{$i}')" class="btn">点击上传</a>

	<?php
		}
	?>
	<div>
		<button type="submit">提交</button>
	</div>
</form>
</div>



</body>
<script type="text/javascript" src="/static/js/jquery-1.11.0.min.js"></script>
<script type="text/javascript">

function getImgUrl(sourceId) {
	let url
    if (navigator.userAgent.indexOf("MSIE")>=1) { // IE
        url = document.getElementById(sourceId).value
    } else if(navigator.userAgent.indexOf("Firefox")>0) { // Firefox
        url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0))
    } else if(navigator.userAgent.indexOf("Chrome")>0) { // Chrome
        url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0))
    }
    return url
}

function previewImg(targetId, sourceId) {
	let url = getImgUrl(sourceId)
	let imgEle = document.getElementById(targetId)
	imgEle.src = url		
}

function getUploadInfo() {
	return new Promise(resolve => {
		$.ajax({
			type: "post",
			url: "/index.php/Admin/Index/getUploadInfo",
			success: function(data) {
				resolve(data)
			}
		})
	})
}


function ossUpload(sourceId, bannerId, imgsrcId) {
	let file = document.getElementById(sourceId).files[0]
	let fileName = file.name
	getUploadInfo().then(res => {
		// console.log(JSON.parse(res))
		let data = JSON.parse(res)
		let suffix = get_suffix(fileName)
        let imgName = `${random_string(10)}${suffix}`
        let keyImgName = `${data.dir}${imgName}`
		let formData = new FormData()
		formData.append('key', keyImgName)
		formData.append('policy', data.policy)
		formData.append('OSSAccessKeyId', data.accessid)
		formData.append('success_action_status', '200')
		formData.append('callback', data.callback)
		formData.append('signature', data.signature)
		formData.append('file', file)
		// console.log(formData.get('key'))

		$.ajax({
	        url: data.host,
	        data: formData,
	        processData: false,
	        cache: false,
	        async: false,
	        type:'POST',
	        contentType: false,
	        success: function (data, textStatus, request) {
	           
	            if (textStatus == 'success') {
	            	document.getElementById(bannerId).src = `https://neimengweixin.cdn.xianyugame.com/${keyImgName}`
	            	document.getElementById(imgsrcId).value = `https://neimengweixin.cdn.xianyugame.com/${keyImgName}`
	            }

	        },
	        error : function(responseStr) {
	            console.log(responseStr)
	        }
	    })
	})

}



function random_string(len) {
　　len = len || 32;
　　var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';   
　　var maxPos = chars.length;
　　var pwd = '';
　　for (i = 0; i < len; i++) {
    　　pwd += chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return pwd;
}

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}



</script>
</html>